package com.wz.controller;


import com.wz.bean.User;
import com.wz.common.bean.PageBean;
import com.wz.common.bean.ResultBean;
import com.wz.common.controller.BaseController;
import com.wz.service.UserService;
import com.wz.token.TokenContext;
import com.wz.utils.MD5Util;
import com.wz.utils.MapUtil;
import com.wz.utils.StringUtil;
import com.wz.validate.UserSaveValidate;
import com.wz.validate.UserUpdateValidate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>Project: wz_api - UserController
 * <p>Powered by pisces On 2022-01-13 13:47:52
 * <P>Created by IntelliJ IDEA
 *
 * @author ww606851@163.com
 * @version 1.0
 * @description:
 * @since 8
 */

@RestController
@Api(tags = "用户管理")
public class UserController extends BaseController {
	@Autowired
	UserService userService;
	@Autowired(required = false)
	TokenContext tokenContext;

	@PostMapping("/hello")
	@ApiOperation("查询用户列表")
	public ResultBean hello(@RequestBody Map map) {
		PageBean bean = userService.query(map);
		return success(bean);
	}

	@PostMapping("/save")
	@ApiOperation("保存用户")
	public ResultBean save(@RequestBody @Validated(UserSaveValidate.class) User user, BindingResult result) {
		Map rs = validate(result);
		if (rs.size() > 0) return validateFail(rs);
		int r = userService.save(user);
		return r > 0 ? success(Message.SAVE_SUCCESS) : fail(Message.SAVE_FAIL);
	}

	@PostMapping("/update")
	@ApiOperation("修改用户信息")
	public ResultBean update(@RequestBody @Validated(UserUpdateValidate.class) User user, BindingResult result) {
		Map rs = validate(result);
		if (rs.size() > 0) return validateFail(rs);
		return fail("no");
	}

	@PostMapping("/login")
	public ResultBean login(@RequestBody Map map) {
		// 判断用户名不能为空
		String username = MapUtil.getValue(map, "username");
		if (StringUtil.isEmpty(username)) return fail("用户名不能为空！！！");
		// 判断密码不能为空
		String pwd = MapUtil.getValue(map, "password");
		if (StringUtil.isEmpty(pwd)) return fail("密码不能为空！！");
		//根据就用户名查询用户信息
		Map rs = userService.queryByName(username);
		if (rs == null) return fail("该账号不存在！");
		String enpwd = MD5Util.getMD5(pwd);
		String dbpwd = MapUtil.getValue(rs, "password");
		if (!enpwd.equals(dbpwd)) return fail("密码不正确！");
		int status = MapUtil.getIntValue(rs, "status");
		if (status != 1) return fail("该账号没有权限！");
		// 生成token，登录成功
		String token = tokenContext.generateToken(rs);
		rs.put("token", token);
		return success("登录成功！", rs);
	}
}
